package com.intelligent.eayon.handler;

import com.intelligent.eayon.dto.ResponseDto;
import com.intelligent.eayon.message.MessageHead;
import com.intelligent.eayon.message.Response;
import com.intelligent.eayon.message.TransMessage;
import com.intelligent.eayon.utils.AppConstant;
import com.intelligent.eayon.utils.ByteUtils;
import com.intelligent.eayon.utils.MessageUtils;
import com.intelligent.ispc.common.utils.ApplicationException;
import com.intelligent.ispc.common.utils.ExceptionMessages;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class SignUpHandler extends ChannelInboundHandlerAdapter {

    private static Logger logger = LoggerFactory.getLogger(SignUpHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        logger.info("Sign Up begin.");

        logger.info(msg.toString());

        logger.info("Sign Up end.");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        ResponseDto responseDto = new ResponseDto();
        if (cause instanceof ApplicationException) {
            ApplicationException applicationException = (ApplicationException) cause;
            int code = AppConstant.REQ_SIGN;
            responseDto.setCode(code);
            responseDto.setErrc(applicationException.getCode()); // set error code
            responseDto.setAtlg(0);

            Response response = MessageUtils.responseDtoEncoder(responseDto);

            TransMessage message = MessageUtils.buidReturnMsg(response);
            ctx.writeAndFlush(message);
            logger.error("exceptionCaught from SignUpHandler: " + applicationException.getMessage());

        } else {
            MessageHead messageHead = new MessageHead();

            byte[] error = ByteUtils.intToBytes(ExceptionMessages.ERR_20001);
            byte[] errc = new byte[6];
            for (int i = 2; i < 6; i++) {
                errc[i] = error[i - 2];
            }
            messageHead.setErrc(errc);

            TransMessage message = MessageUtils.buildTransMessage(messageHead, null);
            ctx.writeAndFlush(message);
            logger.error("exceptionCaught from SignUpHandler: " + cause);
            cause.printStackTrace();
        }
    }
}
